<template>
  <hm-layout>
    <view class="container">
      <view class="container-inner">
        <div class="tips-wrapper">
          <div class="desc wow fadeInUp" style="visibility: visible; animation-name: fadeInUp;">
            <h3>温馨提示：</h3>
            <p class="tips-item">1、申请提现5个工作日内结算提现申请，现阶段仅支持微信提现。</p>
            <p class="tips-item">2、微信提现：必须填写微信认证真实收款人姓名，上传微信收款二维码（不可截图）。</p>
            <p class="tips-item">3、提现收取5%手续费，系统自动扣除，节假日可能顺延到下个工作日，请耐心等待。</p>
          </div>
        </div>
        <div class="desc wow fadeInUp" style="visibility: visible; animation-name: fadeInUp; margin-top: 40rpx;">
          <h3 class="payment-title">收款账户：</h3>
          <el-card v-if="userInfo.wechat_payment_code_url && userInfo.wechat_payment_real_name" shadow="always" class="payment-account-card">
            <div class="payment-account-item">
              <div class="payment-account-radio">
                <el-radio v-model="paymentAccountId" label="1"> &nbsp;</el-radio>
              </div>
              <el-image class="payment-account-img" :src="userInfo.wechat_payment_code_url" />
              <div class="payment-account-content">
                <div class="payment-account-type">支付方式：微信</div>
                <div class="payment-account-name">收款人姓名：{{ userInfo.wechat_payment_real_name }}</div>
              </div>
            </div>
          </el-card>
          <el-button v-else icon="plus" type="primary" @click="handlePaymentInfo">填写收款信息</el-button>
        </div>
        <div class="balance-info-wrap">
          <el-image src="/static/gold.png" fit="contain" class="commission-icon" />
          <div class="balance-info-sum-wrap">
            <p>可提现金额：</p>
            <p class="balance-info-sum">{{ vk.pubfn.priceFilter(userInfo.balance) }}</p>
          </div>
          <el-button type="primary" class="balance-info-btn" @click="handleApplyCashOut">提现</el-button>
        </div>
        <div class="commission-wrap">
          <div class="commission-col">
            <div class="commission-col-sum">{{ vk.pubfn.priceFilter(userInfo.total_revenue) }}</div>
            <div class="commission-col-label">累计收益</div>
          </div>
          <div class="commission-col">
            <div class="commission-col-sum">{{ vk.pubfn.priceFilter(cashOutInfo.completed) }}</div>
            <div class="commission-col-label">累计提现</div>
          </div>
          <div class="commission-col">
            <div class="commission-col-sum">{{ vk.pubfn.priceFilter(cashOutInfo.waiting) }}</div>
            <div class="commission-col-label">提现中</div>
          </div>
        </div>
        <el-table :data="cashOutTableData" empty-text="暂无数据">
          <el-table-column prop="created_at" label="创建时间" width="180" :formatter="(row, _, cellValue) => vk.pubfn.timeFormat(cellValue)" />
          <el-table-column prop="status" label="状态" :formatter="(row, _, cellValue) => cellValue === 1 ? '待打款' : '打款成功'" />
          <el-table-column prop="amount" label="提现金额（元）" :formatter="(row, _, cellValue) => vk.pubfn.priceFilter(cellValue)" />
          <el-table-column prop="charge" label="手续费（元）" :formatter="(row, _, cellValue) => vk.pubfn.priceFilter(cellValue)" />
          <el-table-column prop="_id" label="单号" />
        </el-table>
      </view>
    </view>
    <el-dialog v-model="paymentDialogVisible" title="收款信息" width="800px">
      <el-form :model="paymentInfo" :rules="paymentInfoRules">
        <el-form-item label="真实姓名" prop="wechat_payment_real_name">
          <el-input v-model="paymentInfo.wechat_payment_real_name" />
        </el-form-item>
        <el-form-item label="微信收款二维码" prop="wechat_payment_code_url">
          <hm-upload :value="paymentInfo.wechat_payment_code_url" @success="handleUploadSuccess"></hm-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="payment-dialog-footer">
          <el-button @click="paymentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitPaymentInfo">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="cashOutDialogVisible" title="申请提现" width="600px">
      <el-form :model="cashOutForm" :rules="cashOutRules" label-width="160px" class="cash-out-form">
        <el-form-item label="申请提现金额（元）" prop="amount">
          <el-input-number v-model="cashOutForm.amount" controls-position="right" class="cash-out-form-amount"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="提现手续费用（元）" prop="charge">
          <el-input v-model="cashOutForm.charge" disabled />
        </el-form-item>
        <el-form-item label="实际到账金额（元）" prop="received">
          <el-input v-model="cashOutForm.received" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="payment-dialog-footer">
          <el-button @click="cashOutDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitCashOut">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </hm-layout>
</template>

<script setup>
import { ref, unref, watchEffect, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
const userInfo = ref({})
console.log('user info : ', userInfo)
const paymentDialogVisible = ref(false)
const paymentInfo = ref({ wechat_payment_real_name: '', wechat_payment_code_url: '' })
const paymentInfoRules = ref({
  wechat_payment_real_name: [
    { required: true, message: '请填写真实姓名', trigger: 'blur' }
  ],
  wechat_payment_code_url: [
    { required: true, message: '请上传微信收款二维码', trigger: 'blur' }
  ]
})
const paymentAccountId = ref('1')
const cashOutInfo = ref({ completed: 0, waiting: 0 })
const cashOutTableData = ref([])

function getUserInfo() {
  vk.callFunction({
    url: 'client/user/kh/walletOverview',
    title: '请求中...',
    data: {},
  }).then((res) => {
    if (res.code === 0) {
      userInfo.value = res.data
    }
  });
}

function getCashInfo() {
  vk.callFunction({
    url: 'client/user/kh/cashOutOverview',
    title: '请求中...',
    data: {},
  }).then((res) => {
    if (res.code === 0) {
      cashOutInfo.value = res.data
    }
  });
}

function getCashTableData() {
  vk.callFunction({
    url: 'client/user/kh/getCashOutList',
    title: '请求中...',
    data: {},
  }).then((res) => {
    cashOutTableData.value = res.data
  });
}

function handlePaymentInfo() {
  paymentDialogVisible.value = true
}

function handleUploadSuccess(imgUrl) {
  paymentInfo.value.wechat_payment_code_url = imgUrl
}

function handleSubmitPaymentInfo() {
  vk.callFunction({
    url: 'client/user/kh/updatePaymentInfo',
    title: '请求中...',
    data: {
      ...unref(paymentInfo)
    },
  }).then((res) => {
    ElMessage.success(res.msg || '更新成功')
    paymentDialogVisible.value = false
    getUserInfo()
  }).catch(err => {
    ElMessage.error(err.msg || '更新失败')
  });
}

const cashOutDialogVisible = ref(false)
const cashOutForm = ref({ amount: 0, charge: 0, received: 0 })
const cashOutRules = ref({
  amount: [
    { required: true, message: '提现金额（元）必填' }
  ]
})

watchEffect(() => {
  const charge = parseInt(cashOutForm.value.amount * 100 * 0.05)
  cashOutForm.value.charge = vk.pubfn.priceFilter(charge)
  cashOutForm.value.received = vk.pubfn.priceFilter(parseInt(cashOutForm.value.amount * 100 - charge))
})

function handleApplyCashOut() {
  if (!userInfo.value.wechat_payment_code_url || !userInfo.value.wechat_payment_real_name) {
    ElMessage.warning('请先完善收款信息')
    return
  }
  cashOutForm.value = { amount: 0, charge: 0, received: 0 }
  cashOutDialogVisible.value = true
}

function handleSubmitCashOut() {
  const formatedAmount = cashOutForm.value.amount * 100
  if (formatedAmount > userInfo.balance) {
    ElMessage.warning('余额不足')
    return
  }
  if (formatedAmount === 0) {
    ElMessage.warning('提现金额必须大于0')
    return
  }

  vk.callFunction({
    url: 'client/user/kh/createCashOut',
    title: '请求中...',
    data: {
      balance: formatedAmount
    },
  }).then(res => {
    if (res.code === 0) {
      ElMessage.success(res.msg || '提现申请已提交')
      cashOutDialogVisible.value = false
      getUserInfo()
      getCashInfo()
      getCashTableData()
    } else {
      ElMessage.warning(res.msg || '提现异常，请联系管理员')
    }
  }).catch((err) => {
    console.log('提现异常 ： ', err)
    ElMessage.warning('提现异常，请联系管理员')
  });
}

onMounted(() => {
  getUserInfo()
  getCashInfo()
  getCashTableData()
})
</script>

<style lang="scss">
.container {
  padding: 30px;

  .container-inner {
    width: 1200px;
    margin: auto;

    .desc {
      color: #5e656f;
      font-size: 16px;

      h3 {
        font-size: 16px;
        color: #f57286;
      }
    }

    .tips-item {
      margin-top: 10rpx;
    }

    .payment-title {
      margin-bottom: 24rpx;
    }

    .payment-dialog-footer {
      width: 100%;
      display: flex;
      justify-content: flex-end;
    }

    .balance-info-wrap {
      margin-top: 48rpx;
      margin-bottom: 48rpx;
      padding: 40rpx;
      display: flex;
      align-items: center;
      border-radius: 16rpx;
      background: #e9eef599;
      width: fit-content;
    }

    .commission-icon {
      width: 84rpx;
      height: 84rpx;
    }

    .balance-info-sum-wrap {
      margin: 0 24rpx 0 48rpx;
    }

    .balance-info-sum {
      color: #f57286;
      font-weight: 700;
      font-size: 64rpx;
    }

    .balance-info-btn {
      background: linear-gradient(45deg, #6b57cc 0%, #b652c3 50%, #eca08c 100%);
      border: none;
    }

    .commission-wrap {
      display: flex;
      align-items: center;
      margin-bottom: 48rpx;
    }

    .commission-col {
      padding: 0 100rpx;
      border-right: 1px solid #e5e7eb;
      text-align: center;

      &:last-child {
        border-right: none;
      }
    }

    .commission-col-sum {
      font-size: 48rpx;
      color: #f57286;
      line-height: 72rpx;
    }

    .commission-col-label {
      font-size: 13px;
      color: #60636a;
    }
  }
}



.cash-out-form {
  padding-left: 11px;

  .cash-out-form-amount {
    :deep(.el-input__inner) {
      text-align: left;
    }

    :deep(.el-input__wrapper) {
      padding-left: 11px;
    }
  }
}

.payment-account-card {
  width: 720rpx;
}
.payment-account-item {
  width: 100%;
  display: flex;
  padding: 20rpx 0;
  align-items: center;
}
.payment-account-radio {
  margin-right: 20rpx;
}
.payment-account-img {
  width: 160rpx;
  height: 160rpx;
  margin-right: 20rpx;
}
.payment-account-content {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  height: 120rpx;
}
</style>
